package com.hliushi.bookmanager.controller.user;

import com.hliushi.bookmanager.mapper.BookMapper;
import com.hliushi.bookmanager.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user/book")
public class UserBookController {
    @Autowired
    private BookMapper bookMapper;

    @RequestMapping("/getAll")
    public String getAll(Model model) {
        List<Book> books = bookMapper.getAllBook();
        model.addAttribute("books", books);
        return "user/books";
    }

    @RequestMapping("/info/{id}")
    public String info(Model model, @PathVariable("id") String id) {
        Book book = bookMapper.getBookById(id);
        model.addAttribute("book", book);
        return "user/book_info";
    }

    @RequestMapping("/search")
    public String search(String keyword, Model model) {
        List<Book> books = bookMapper.searchBook(keyword);
        model.addAttribute("books", books);
        return "user/book_search_result";
    }

    @RequestMapping("/borrow/{bookId}/{readerId}")
    public String borrow(@PathVariable String readerId, @PathVariable String bookId) throws Exception {


        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-HH-mm-ss");
        SimpleDateFormat sdf02 = new SimpleDateFormat("yyyy-MM-dd");
        String serNum = sdf.format(date);
        serNum = serNum.replace("-", "");
        String lendDate = sdf02.format(date);


        System.out.println("serNum = " + serNum);
        System.out.println("lendDate = " + lendDate);

        bookMapper.borrowBook(serNum, bookId, readerId, lendDate);
        bookMapper.updateBookState(bookId, 0);
        return "redirect:/user/record/getOwnRecord";
    }


    @RequestMapping("/back/{bookId}")
    public String backBook(@PathVariable String bookId) {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String backTime = sdf.format(date);
        bookMapper.backBook(bookId, backTime);
        bookMapper.updateBookState(bookId, 1);

        return "redirect:/user/record/getOwnRecord";
    }
}
